package demo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.fastinfoset.Encoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

    private static Logger logger = LoggerFactory.getLogger(StringUtil.class);


    /**
     * 测试正则
     */
    public static void testReg(){

        String test_one = "jjj343kkjn5jk2j3hf13sdf15s1d511gasb5rh9r843hiu54hg7h54h29hbdfh9";
        String test_two = "n0fjfj489y54uy73023hrfih2938y7384sa1df15sd1f561sda1vrt7rh20r0br02";
        String test_three = "fjsdaf88h8hf84h7gf9hhg2vh0hf482hgfd23dj9f84hfsd11s3d1v351sd35af";
        String test_four = "fj28978fj102edh8fg8fn0d803gh9ddnh823gf3pq12hdfsd5153s0dv1sd56165c3";

        System.out.println("------ 1.匹配 begin -----");
        System.out.println("one: "+test_one);
        String reg = "\\d+";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = null;
        matcher = pattern.matcher(test_one);
        System.out.println(matcher.find());
        System.out.println("------ 1.匹配 end -----");
        System.out.println();
        System.out.println("------ 2.获取 begin -----");
        System.out.println("two: "+test_two);
        matcher = pattern.matcher(test_two);
        while (matcher.find()) {
            System.out.println(matcher.group(0));
        }
        System.out.println("------ 2.获取 end -----");
        System.out.println("------ 3.替换 begin -----");
        System.out.println("three: "+test_three);
//        test_three = test_three.replaceAll("[1,2,3,4,5]","#");
        test_three = test_three.replaceAll("[12345]","#");
        test_three = test_three.replaceAll("[6789]","*");
        System.out.println(test_three);
        System.out.println("------ 3.替换 end -----");
        System.out.println("------ 4.切割 begin -----");
        System.out.println("four: "+test_four);
        String []list = test_four.split(reg);
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("------ 4.切割 end -----");
    }


    /**
     * 测试log日志
     */
    public static void testLogger(){
        logger.error("woshierror");
        logger.debug("我是debug");
        logger.info("我是-info");
        logger.warn("sss-warn");
    }


    /**
     * 遍历JSONArray
     */
    public static void soutJSONArray(JSONArray jsonArray) {
        JSONObject jsonObject;
        System.out.println("-----------------------");
        for (Object object : jsonArray) {
            try {
                jsonObject = (JSONObject) object;
            } catch (Exception e) {
                System.out.println(object.getClass().getName()+"\t---\t"+object);
                continue;
            }
            Set<String> keys = jsonObject.keySet();
            for (Object key : keys) {
                System.out.print(key + "\t===\t");
                System.out.println(jsonObject.get(key));
            }
            System.out.println("-----------------------");
        }
    }

    public static void soutJSONArray(String jsonArrayString) {
        JSONArray jsonArray = JSON.parseArray(jsonArrayString);
        soutJSONArray(jsonArray);
    }

    /**
     *1. 从剪切板获得文字。
     */
    public static String getSysClipboardText() {
        String ret = "";
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪切板中的内容
        Transferable clipTf = sysClip.getContents(null);

        if (clipTf != null) {
            // 检查内容是否是文本类型
            if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    ret = (String) clipTf
                            .getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return ret;
    }

    /**
     * 2.将字符串复制到剪切板。
     */
    public static void setSysClipboardText(String writeMe) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(writeMe);
        clip.setContents(tText, null);
    }

    /**
     *3. 从剪切板获得图片。
     */
    public static Image getImageFromClipboard() throws Exception {
        Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable cc = sysc.getContents(null);
        if (cc == null)
            return null;
        else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
            return (Image) cc.getTransferData(DataFlavor.imageFlavor);
        return null;

    }
    /**
     * 4.复制图片到剪切板。
     */
    public static void setClipboardImage(Image image)throws Exception {
        Transferable trans = new Transferable() {
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[] { DataFlavor.imageFlavor };
            }

            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(flavor);
            }

            public Object getTransferData(DataFlavor flavor)
                    throws UnsupportedFlavorException, IOException {
                if (isDataFlavorSupported(flavor))
                    return image;
                throw new UnsupportedFlavorException(flavor);
            }

        };
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
                null);
    }
    /**
     * 5.通过流获取，可读取图文混合
     */
    public void getImageAndTextFromClipboard() throws Exception{
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable clipTf = sysClip.getContents(null);
        DataFlavor[] dataList = clipTf.getTransferDataFlavors();
        int wholeLength = 0;
        for (int i = 0; i < dataList.length; i++) {
            DataFlavor data = dataList[i];
            if (data.getSubType().equals("rtf")) {
                Reader reader = data.getReaderForText(clipTf);
                OutputStreamWriter osw = new OutputStreamWriter(
                        new FileOutputStream("d:\\test.rtf"));
                char[] c = new char[1024];
                int leng = -1;
                while ((leng = reader.read(c)) != -1) {
                    osw.write(c, wholeLength, leng);
                }
                osw.flush();
                osw.close();
            }
        }
    }

    // 粘贴剪切板中的图片到指定目录
    public  static void pasteImg(String pathName) throws Exception {
        Image image = getImageFromClipboard();
        if (image == null) {
            return;
        }
        File file = new File(pathName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
//                file.getParentFile().mkdir();
            }
            file.createNewFile();
        }
        ImageIO.write( (RenderedImage)image, "png", file);
        setClipboardImage(null);
    }

//    public static void main(String[] args) throws Exception {
//        String res = "abcd";
//        String str;
//        str = new String(RandomUtils.nextBytes(6),"unicode");
////        str = RandomStringUtils.random(20, 'a','b','c','d','e','f','1','1','2');
////        str = RandomStringUtils.random(20,true,true);
//        str = RandomStringUtils.random(20, "56548ggyftidyt15/+/+//-")+"___"+DateUtil.getNow();
//        setSysClipboardText(str);
//        System.out.println(getSysClipboardText());
//        System.out.println("begin...");
//        while (true) {
//            Thread.sleep(Long.parseLong("1000"));
//            try {
//                pasteImg("d://test/ttd/ts/d/" + new Date().getTime()+".png");
//            } catch (Exception e) {
//                System.out.println("get error");
//                setClipboardImage(null);
//            }
//        }
//    }

    public static void main(String[] args) {
        String test = getFileContent(path);
        System.out.println(test.length());
    }

    public static boolean isTrue(String res,String text){
        res = res.replace(",", " ").trim();
        text = text.replace(",", " ").trim();
        String[] str1 = res.split(" ");
        String[] str2 = text.split(" ");
        Arrays.sort(str1);
        Arrays.sort(str2);
        return JSON.toJSONString(str1).equals(JSON.toJSONString(str2));
    }

    public static String randomStr(int count) {
        return randomStr(count, true, false);
    }
    public static String randomStrNum(int count){
        return randomStr(count, true, true);
    }

    public static String randomNum(int count) {
        return randomStr(count, false, true);
    }
    public static String randomStr(int count, boolean letters, boolean numbers) {
        return RandomStringUtils.random(count, letters, numbers);
    }

    public static void outPut(Object obj){
        String text = JSON.toJSONString(obj);
        outPut(text);
    }

    static String path = "C:\\Users\\mayn\\Desktop\\out\\" + DateUtil.getDateToday() + "testMax"+".json";


    public static void outPut(String text){
        try (PrintWriter pw = new PrintWriter(new File(path))) {
            pw.write(text);
            pw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void outPutAppend(Object obj) {
        outPutAppend(JSON.toJSONString(obj));
    }

    public static void outPutAppend(String text){
        String path = "C:\\Users\\mayn\\Desktop\\out\\" + DateUtil.getDateToday()+"testMax" + ".json";
        fileAppendContent(path, "\n"+text);
    }

    /**
     * 给文件后边添加文本内容
     * @param filePath 文件地址
     * @param content 内容
     * @return 成功
     */
    private static boolean fileAppendContent(String filePath, String content) {
        String text = getFileContent(filePath);
        logger.info(String.valueOf(text.length()));
        text = text + content;
        try (PrintWriter pw = new PrintWriter(filePath)) {
            pw.write(text);
            pw.flush();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取文件内容
     * @param filePath 文件地址
     * @return 文本内容
     */
    private static String getFileContent(String filePath) {
        //获得文件编码
        String text;
        InputStream is = null;
        try {
            is = new FileInputStream(new File(filePath));
            text = IOUtils.toString(is, Encoder.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            text = "";
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return text;
    }


}
